package com.lie.prepare.multi_thread.queue;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by lie on 2018/4/9.
 * 生产吐司
 */
public class Toaster implements Runnable {

    private ToastQueue toastQueue;

    private int count = 0;
    private Random random = new Random(47);

    public Toaster(ToastQueue toastQueue) {
        this.toastQueue = toastQueue;
    }

    public void run() {
        //补充语法知识
        //这里的while要放到try里面，而不是外面
        //否则shutdown引起的InterruptedException被catch了以后，while是停不下来的
        try{
            while (!Thread.interrupted()) {

                TimeUnit.MILLISECONDS.sleep(100 + random.nextInt(500));
                //make toast
                Toast toast = new Toast(count++);
                System.out.println("准备放进队列里的 "+toast);
                //放进队列里
                toastQueue.put(toast);
            }
        }catch (InterruptedException e) {
            System.out.println("ToastTask interrupted");
        }

        System.out.println("ToastTask off");
    }
}
